#include "../ui.h"
#include "../../lvgl/src/core/lv_obj.h"
#include <stdio.h>
#include <string.h>

#ifndef LV_EVENT_USER
#define LV_EVENT_USER 0x1000
#endif

// 1. 声明结构体和函数原型（解决声明缺失问题）
typedef struct
{
    lv_obj_t * screen;  // 目标屏幕
    NetResponse * resp; // 网络响应数据
} EventPostData_S1;
#define SCREEN1_ID 1
// 提前声明函数，避免隐式声明错误
static void event_post_timer_cb(lv_timer_t * timer);
static void ui_Screen1_handle_direct(NetResponse * resp, lv_obj_t * screen);

// 全局UI组件定义
lv_obj_t * ui_Screen1;
lv_obj_t * ui_Keyboard_s1;
lv_obj_t * ui_account_text_s1;
lv_obj_t * ui_password_text_s1;
lv_obj_t * ui_button_login_s1;
lv_obj_t * ui_button_register_s1;
lv_obj_t * ui_label_login_s1;
lv_obj_t * ui_label_register_s1;
static void timer_auto_del_msgbox(lv_timer_t * timer)
{
    if(timer->user_data) {
        lv_obj_del(timer->user_data); // 删除提示框
    }
    lv_timer_del(timer); // 删除自身
}
// 2. 定时器回调（移到全局作用域，解决嵌套定义错误）
static void event_post_timer_cb(lv_timer_t * timer)
{
    if(!timer) return;

    // 低版本LVGL兼容：直接访问定时器的user_data（假设timer结构体有user_data成员）
    EventPostData_S1 * post_data = (EventPostData_S1 *)timer->user_data;
    if(!post_data || !post_data->screen || !post_data->resp) {
        lv_timer_del(timer);
        return;
    }

    // 调用直接响应处理函数
    ui_Screen1_handle_direct(post_data->resp, post_data->screen);

    // 释放资源
    lv_timer_del(timer);
    free(post_data);
    printf("[LOGIN-CB] 定时器资源已释放\n");
}

// 3. 网络回调函数（修改定时器创建逻辑，兼容低版本）
static void login_net_callback(NetResponse * resp)
{
    printf("[LOGIN-CB] 进入登录网络回调函数\n");
    if(!resp || !resp->user_data) { // 检查 resp 和 user_data 非空
        if(resp) {
            if(resp->data) free(resp->data);
            free(resp);
        }
        printf("[LOGIN-CB] 错误：resp或user_data为空\n");
        return;
    }

    // 关键修改：直接将 user_data 转换为控件指针（不再解析为标识）
    lv_obj_t * screen = (lv_obj_t *)resp->user_data;
    // 仅检查指针非空（低版本 LVGL 最安全的有效性判断）
    if(!screen) {
        printf("[LOGIN-CB] 错误：屏幕指针为空\n");
        if(resp->data) free(resp->data);
        free(resp);
        return;
    }

    // （可选）简单检查屏幕是否为当前活动屏幕（避免已切换界面的无效指针）
    if(screen != lv_scr_act()) {
        printf("[LOGIN-CB] 警告：屏幕非当前活动屏，但仍继续处理\n");
    }

    // 后续创建 EventPostData_S1 和定时器的逻辑不变...
    EventPostData_S1 * post_data = (EventPostData_S1 *)malloc(sizeof(EventPostData_S1));
    if(!post_data) {
        printf("[LOGIN-CB] 错误：暂存数据内存分配失败\n");
        if(resp->data) free(resp->data);
        free(resp);
        return;
    }
    post_data->screen = screen;
    post_data->resp   = resp;

    lv_timer_t * timer = lv_timer_create(event_post_timer_cb, 0, post_data);
    if(!timer) {
        printf("[LOGIN-CB] 错误：定时器创建失败\n");
        free(post_data);
        if(resp->data) free(resp->data);
        free(resp);
        return;
    }

    printf("[LOGIN-CB] 事件已投递到UI线程（低版本兼容）\n");
}

// 登录按钮点击事件
void ui_event_button_login_s1(lv_event_t * e)
{
    lv_event_code_t event_code = lv_event_get_code(e);
    if(event_code == LV_EVENT_CLICKED) {
        printf("处理点击事件\n");
        lv_obj_add_flag(ui_button_login_s1, LV_OBJ_FLAG_USER_1);

        const char * account  = lv_textarea_get_text(ui_account_text_s1);
        const char * password = lv_textarea_get_text(ui_password_text_s1);
        printf("从文本框获取账号密码\n");

        if(strlen(account) == 0 || strlen(password) == 0) {
            lv_obj_t * msgbox = lv_msgbox_create(ui_Screen1, "notice", "account or password can't be void", NULL, true);
            lv_obj_align(msgbox, LV_ALIGN_CENTER, 0, 0);
            // 添加1秒自动关闭
            lv_timer_t * timer = lv_timer_create(timer_auto_del_msgbox, 1000, msgbox);
            lv_timer_set_repeat_count(timer, 1); // 只执行一次
            lv_obj_clear_flag(ui_button_login_s1, LV_OBJ_FLAG_USER_1);
            return;
        }

        LoginRequest req = {.account = account, .password = password};
        printf("序列化登录请求\n");
        char * send_data = protocol_serialize_login(&req);
        if(!send_data) {
            lv_obj_t * msgbox = lv_msgbox_create(ui_Screen1, "notice", "shu ju ge shi cuo wu", NULL, true);
            lv_obj_align(msgbox, LV_ALIGN_CENTER, 0, 0);
            // 添加1秒自动关闭
            lv_timer_t * timer = lv_timer_create(timer_auto_del_msgbox, 1000, msgbox);
            lv_timer_set_repeat_count(timer, 1); // 只执行一次
            lv_obj_clear_flag(ui_button_login_s1, LV_OBJ_FLAG_USER_1);
            return;
        }

        bool send_ret = net_client_send(MSG_TYPE_LOGIN, send_data, login_net_callback, ui_Screen1);
        if(send_ret) {
            printf("发送成功\n");
        } else {
            printf("发送失败\n");
            lv_obj_t * msgbox = lv_msgbox_create(ui_Screen1, "Error", "Failed to send request", NULL, true);
            lv_obj_align(msgbox, LV_ALIGN_CENTER, 0, 0);
            lv_timer_t * timer = lv_timer_create(timer_auto_del_msgbox, 1000, msgbox);
            lv_timer_set_repeat_count(timer, 1);
            lv_obj_clear_flag(ui_button_login_s1, LV_OBJ_FLAG_USER_1);
        }
        free(send_data);
        printf("[LOGIN-BTN] 已释放序列化内存\n");
    }
}

// 4. 直接响应处理函数（解决静态声明冲突）
static void ui_Screen1_handle_direct(NetResponse * resp, lv_obj_t * screen)
{
    printf("[RESP-HDL] 进入直接响应处理函数\n");
    if(!resp || !screen) {
        printf("[RESP-HDL] 错误：响应数据或屏幕为空\n");
        if(resp) {
            if(resp->data) free(resp->data);
            free(resp);
        }
        return;
    }
    // 处理网络错误
    if(resp->code != 0) {
        const char * err_msg = "Network error";
        if(resp->code == -2)
            err_msg = "Failed to connect to server";
        else if(resp->code == -3)
            err_msg = "Failed to send data";
        else if(resp->code == -4)
            err_msg = "Failed to receive response";
        else if(resp->code == -6)
            err_msg = "Server closed connection, retry";

        lv_obj_t * msgbox = lv_msgbox_create(screen, "Error", err_msg, NULL, true);
        lv_obj_align(msgbox, LV_ALIGN_CENTER, 0, 0);
        lv_timer_t * timer = lv_timer_create(timer_auto_del_msgbox, 1000, msgbox);
        lv_timer_set_repeat_count(timer, 1);

        if(resp->data) free(resp->data);
        free(resp);
        if(lv_obj_is_valid(ui_button_login_s1)) {
            lv_obj_clear_flag(ui_button_login_s1, LV_OBJ_FLAG_USER_1);
        }
        return; // 网络错误处理完成，返回
    }

    // 解析响应数据
    // 解析响应数据：添加严格的边界检查
    LoginResponse login_resp = {0};
    bool parse_ok            = false;

    if(resp->data) {
        // 关键：检查 resp->data 长度（避免解析时越界）
        size_t data_len = strlen(resp->data);
        printf("[RESP-HDL] 响应数据长度：%zu，内容：%s\n", data_len, resp->data);

        // 若服务器返回格式为 "success:xxx" 或 "fail:xxx"，可先检查前缀
        if(data_len < 6) { // 最小合法长度（如 "fail:x" 共5字符）
            printf("[RESP-HDL] 响应数据过短，无法解析\n");
            parse_ok = false;
        } else {
            printf("解析返回数据\n");
            parse_ok = protocol_deserialize_login(resp->data, &login_resp);
            printf("返回的msg%s\n",login_resp.msg);
        }
    } else {
        printf("[RESP-HDL] 错误：服务器返回空数据\n");
        parse_ok = false;
    }

    if(!parse_ok) {
        lv_obj_t * msgbox = lv_msgbox_create(screen, "Error", "Failed to parse response", NULL, true);
        lv_obj_align(msgbox, LV_ALIGN_CENTER, 0, 0);
        lv_timer_t * timer = lv_timer_create(timer_auto_del_msgbox, 1000, msgbox);
        lv_timer_set_repeat_count(timer, 1);
        if(resp->data) free(resp->data);
        free(resp);
        if(lv_obj_is_valid(ui_button_login_s1)) {
            lv_obj_clear_flag(ui_button_login_s1, LV_OBJ_FLAG_USER_1);
        }
        return; // 解析失败处理完成，返回
    }

    // 处理登录结果
    if(login_resp.success) {
        _ui_screen_change(&ui_Screen3, LV_SCR_LOAD_ANIM_FADE_ON, 500, 0, &ui_Screen3_screen_init);
        lv_textarea_set_text(ui_account_text_s1, "");
        lv_textarea_set_text(ui_password_text_s1, "");
    } else {
        printf("登录失败\n");
        const char * err_msg = login_resp.msg ? login_resp.msg : "Login failed";
        lv_obj_t * msgbox    = lv_msgbox_create(screen, "Notice", err_msg, NULL, true);
        lv_obj_align(msgbox, LV_ALIGN_CENTER, 0, 0);
        lv_timer_t * timer = lv_timer_create(timer_auto_del_msgbox, 1000, msgbox);
        lv_timer_set_repeat_count(timer, 1);
    }

    // 释放所有内存
    if(login_resp.msg) {
        free((void *)login_resp.msg);
    }
    if(resp->data) {
        free(resp->data);
    }
    free(resp);
    if(lv_obj_is_valid(ui_button_login_s1)) {
        lv_obj_clear_flag(ui_button_login_s1, LV_OBJ_FLAG_USER_1);
    }
    printf("[RESP-HDL] 直接响应处理完成，内存已释放\n");
}
// 账号输入框事件
void ui_event_account_text_s1(lv_event_t * e)
{
    lv_event_code_t event_code = lv_event_get_code(e);

    if(event_code == LV_EVENT_CLICKED) {
        _ui_keyboard_set_target(ui_Keyboard_s1, ui_account_text_s1);
    }
    if(event_code == LV_EVENT_FOCUSED) {
        _ui_flag_modify(ui_Keyboard_s1, LV_OBJ_FLAG_HIDDEN, _UI_MODIFY_FLAG_REMOVE);
    }
    if(event_code == LV_EVENT_DEFOCUSED) {
        _ui_flag_modify(ui_Keyboard_s1, LV_OBJ_FLAG_HIDDEN, _UI_MODIFY_FLAG_ADD);
    }
}

// 密码输入框事件
void ui_event_password_text_s1(lv_event_t * e)
{
    lv_event_code_t event_code = lv_event_get_code(e);

    if(event_code == LV_EVENT_CLICKED) {
        _ui_keyboard_set_target(ui_Keyboard_s1, ui_password_text_s1);
    }
    if(event_code == LV_EVENT_FOCUSED) {
        _ui_flag_modify(ui_Keyboard_s1, LV_OBJ_FLAG_HIDDEN, _UI_MODIFY_FLAG_REMOVE);
    }
    if(event_code == LV_EVENT_DEFOCUSED) {
        _ui_flag_modify(ui_Keyboard_s1, LV_OBJ_FLAG_HIDDEN, _UI_MODIFY_FLAG_ADD);
    }
}

// 注册按钮事件
void ui_event_button_register_s1(lv_event_t * e)
{
    lv_event_code_t event_code = lv_event_get_code(e);
    if(event_code == LV_EVENT_CLICKED) {
        printf("[REGISTER-BTN] 切换到注册界面\n");
        _ui_screen_change(&ui_Screen2, LV_SCR_LOAD_ANIM_FADE_ON, 500, 0, &ui_Screen2_screen_init);
    }
}

// 初始化登录界面
void ui_Screen1_screen_init(void)
{
    printf("[SCREEN-INIT] 开始初始化登录界面\n");

    ui_Screen1 = lv_obj_create(NULL);
    lv_obj_clear_flag(ui_Screen1, LV_OBJ_FLAG_SCROLLABLE);
    lv_obj_set_style_bg_img_src(ui_Screen1, &ui_img_1931907300, LV_PART_MAIN | LV_STATE_DEFAULT);
    printf("[SCREEN-INIT] 创建主屏幕对象（%p）\n", ui_Screen1);

    ui_Keyboard_s1 = lv_keyboard_create(ui_Screen1);
    lv_obj_set_width(ui_Keyboard_s1, 500);
    lv_obj_set_height(ui_Keyboard_s1, 150);
    lv_obj_set_x(ui_Keyboard_s1, 0);
    lv_obj_set_y(ui_Keyboard_s1, 140);
    lv_obj_set_align(ui_Keyboard_s1, LV_ALIGN_CENTER);
    lv_obj_add_flag(ui_Keyboard_s1, LV_OBJ_FLAG_HIDDEN);
    printf("[SCREEN-INIT] 创建键盘对象（%p）\n", ui_Keyboard_s1);

    ui_account_text_s1 = lv_textarea_create(ui_Screen1);
    lv_obj_set_width(ui_account_text_s1, 404);
    lv_obj_set_height(ui_account_text_s1, 43);
    lv_obj_set_x(ui_account_text_s1, 0);
    lv_obj_set_y(ui_account_text_s1, -90);
    lv_obj_set_align(ui_account_text_s1, LV_ALIGN_CENTER);
    lv_textarea_set_placeholder_text(ui_account_text_s1, "account");
    printf("[SCREEN-INIT] 创建账号输入框（%p）\n", ui_account_text_s1);

    ui_password_text_s1 = lv_textarea_create(ui_Screen1);
    lv_obj_set_width(ui_password_text_s1, 404);
    lv_obj_set_height(ui_password_text_s1, 43);
    lv_obj_set_x(ui_password_text_s1, 0);
    lv_obj_set_y(ui_password_text_s1, -30);
    lv_obj_set_align(ui_password_text_s1, LV_ALIGN_CENTER);
    lv_textarea_set_placeholder_text(ui_password_text_s1, "password");
    printf("[SCREEN-INIT] 创建密码输入框（%p）\n", ui_password_text_s1);

    ui_button_login_s1 = lv_btn_create(ui_Screen1);
    lv_obj_set_width(ui_button_login_s1, 80);
    lv_obj_set_height(ui_button_login_s1, 50);
    lv_obj_set_x(ui_button_login_s1, -80);
    lv_obj_set_y(ui_button_login_s1, 25);
    lv_obj_set_align(ui_button_login_s1, LV_ALIGN_CENTER);
    lv_obj_add_flag(ui_button_login_s1, LV_OBJ_FLAG_SCROLL_ON_FOCUS);
    lv_obj_clear_flag(ui_button_login_s1, LV_OBJ_FLAG_SCROLLABLE);
    printf("[SCREEN-INIT] 创建登录按钮（%p）\n", ui_button_login_s1);

    ui_button_register_s1 = lv_btn_create(ui_Screen1);
    lv_obj_set_width(ui_button_register_s1, 80);
    lv_obj_set_height(ui_button_register_s1, 50);
    lv_obj_set_x(ui_button_register_s1, 80);
    lv_obj_set_y(ui_button_register_s1, 25);
    lv_obj_set_align(ui_button_register_s1, LV_ALIGN_CENTER);
    lv_obj_add_flag(ui_button_register_s1, LV_OBJ_FLAG_SCROLL_ON_FOCUS);
    lv_obj_clear_flag(ui_button_register_s1, LV_OBJ_FLAG_SCROLLABLE);
    printf("[SCREEN-INIT] 创建注册按钮（%p）\n", ui_button_register_s1);

    ui_label_login_s1 = lv_label_create(ui_button_login_s1); // 修正：标签父控件为按钮
    lv_label_set_text(ui_label_login_s1, "login");
    lv_obj_center(ui_label_login_s1); // 标签在按钮内居中
    printf("[SCREEN-INIT] 创建登录标签（%p）\n", ui_label_login_s1);

    ui_label_register_s1 = lv_label_create(ui_button_register_s1); // 修正：标签父控件为按钮
    lv_label_set_text(ui_label_register_s1, "register");
    lv_obj_center(ui_label_register_s1); // 标签在按钮内居中
    printf("[SCREEN-INIT] 创建注册标签（%p）\n", ui_label_register_s1);

    lv_keyboard_set_textarea(ui_Keyboard_s1, ui_account_text_s1);
    lv_obj_add_event_cb(ui_account_text_s1, ui_event_account_text_s1, LV_EVENT_ALL, NULL);
    lv_obj_add_event_cb(ui_password_text_s1, ui_event_password_text_s1, LV_EVENT_ALL, NULL);
    lv_obj_add_event_cb(ui_button_register_s1, ui_event_button_register_s1, LV_EVENT_ALL, NULL);
    lv_obj_add_event_cb(ui_button_login_s1, ui_event_button_login_s1, LV_EVENT_CLICKED, NULL);

    printf("[SCREEN-INIT] 登录界面初始化完成\n");
}

// 销毁登录界面
void ui_Screen1_screen_destroy(void)
{
    printf("[SCREEN-DESTROY] 销毁登录界面\n");
    if(ui_Screen1) lv_obj_del(ui_Screen1);

    ui_Screen1            = NULL;
    ui_Keyboard_s1        = NULL;
    ui_account_text_s1    = NULL;
    ui_password_text_s1   = NULL;
    ui_button_login_s1    = NULL;
    ui_button_register_s1 = NULL;
    ui_label_login_s1     = NULL;
    ui_label_register_s1  = NULL;
}